package com.jhd.fuzhou.view.random;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.view.login.FuzhouApplication;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.DoubleRandomService;
import com.jhd.fuzhou.service.SupervisionService;
import com.jhd.fuzhou.util.CleanSupervisionInspection;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.EditTextView;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.SupervisedUnitVo;
import com.jhd.fuzhou.vo.SupervisionInspectionVo;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.jhd.fuzhou.view.login.MainActivity.supervisionInspectionVo;

public class DoubleStepOneActivity extends BaseActivity {
    private SupervisedUnitVo supervisedUnitVo;
    @BindView(R.id.tv_unitName)TextView tv_unitName;//被监督单位
    @BindView(R.id.tv_creditCode)TextView tv_creditCode;//社会信用代码
    @BindView(R.id.rb_status_1)RadioButton rb_status_1;//经验状态
    @BindView(R.id.rb_status_2)RadioButton rb_status_2;//经验状态
    @BindView(R.id.tv_superviseOffice)TextView tv_superviseOffice;//监督部门
    @BindView(R.id.tv_superviseSector)TextView tv_superviseSector;//监督机构
    @BindView(R.id.tv_legalRepresentative)TextView tv_legalRepresentative;//法人代表
    @BindView(R.id.tv_gender)TextView tv_gender;//性别
    @BindView(R.id.tv_nation)TextView tv_nation;//名族
    @BindView(R.id.tv_contactNumber)TextView tv_contactNumber;//单位电话
    @BindView(R.id.tv_registerAddress)TextView tv_registerAddress;//注册地址
    @BindView(R.id.btn_next)Button btn_next;//下一步
    @BindView(R.id.rel_unitName)RelativeLayout rel_unitName;//去选择单位
    @BindView(R.id.linearLayout)LinearLayout linearLayout;//单位的详情
    private String data;
    private Context context = this;
    private String id;
    private String taskId,isOnlyLook;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_step_one);
    }

    @Override
    protected void processLogic() {
        application.addStepActivity(this);
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        data = getIntent().getStringExtra("data");
        id=getIntent().getStringExtra("id");
        taskId=getIntent().getStringExtra("taskId");
        isOnlyLook = getIntent().getStringExtra("isOnlyLook");
        setData(data,id);
    }
    /*用的是日常监督的，不能用双随机的*/
    private void getDoubleRandomInspectionDetailById(String id){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        DoubleRandomService vs = retrofit.create(DoubleRandomService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("id",id);
        Call<JsonForResult> jsonForResultCall = vs.getSupervisionInspectionDetailById(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        supervisionInspectionVo = JSON.parseObject(jsonForResult.getData().toString(), SupervisionInspectionVo.class);
                        supervisionInspectionVo.setTaskId(taskId);
                        supervisionInspectionVo.setIsOnlyLook(isOnlyLook);
                        getSupervisedUnitById(supervisionInspectionVo.getSupervisedUnitId());
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络错误!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    private void getSupervisedUnitById(String id){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("id",id);
        Call<JsonForResult> jsonForResultCall = vs.getSupervisedUnitById(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        supervisedUnitVo= JSON.parseObject(jsonForResult.getData().toString(), SupervisedUnitVo.class);
                        setUnitVo(supervisedUnitVo);
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络错误!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    private void setUnitVo(SupervisedUnitVo supervisedUnitVo){
        linearLayout.setVisibility(View.VISIBLE);
        tv_unitName.setText(supervisedUnitVo.getUnitName());
        EditTextView.TextViewChange(tv_unitName,context);
        tv_creditCode.setText(supervisedUnitVo.getCreditCode());
        EditTextView.TextViewChange(tv_creditCode,context);
        if (supervisedUnitVo.getBusinessStatus().equals("0")) {
            rb_status_2.setChecked(true);
        } else if (supervisedUnitVo.getBusinessStatus().equals("1")) {
            rb_status_1.setChecked(true);
        }
        tv_superviseOffice.setText(supervisedUnitVo.getSuperviseOffice());
        EditTextView.TextViewChange(tv_superviseOffice,context);
        tv_superviseSector.setText(supervisedUnitVo.getSuperviseSector());
        EditTextView.TextViewChange(tv_superviseSector,context);
        tv_legalRepresentative.setText(supervisedUnitVo.getLegalRepresentative());
        EditTextView.TextViewChange(tv_legalRepresentative,context);
        tv_gender.setText(supervisedUnitVo.getGender());
        EditTextView.TextViewChange(tv_gender,context);
        tv_nation.setText(supervisedUnitVo.getNation());
        EditTextView.TextViewChange(tv_nation,context);
        tv_contactNumber.setText(supervisedUnitVo.getContactNumber());
        EditTextView.TextViewChange(tv_contactNumber,context);
        tv_registerAddress.setText(supervisedUnitVo.getRegisterAddress());
        EditTextView.TextViewChange(tv_registerAddress,context);
    }
    public void setData(String data,String id){
        if(StringUtil.isNullOrEmpty(data)==false) {
            supervisedUnitVo = JSON.parseObject(data, SupervisedUnitVo.class);
            setUnitVo(supervisedUnitVo);
        }else if(StringUtil.isNullOrEmpty(id)==false){
            rel_unitName.setClickable(false);
            getDoubleRandomInspectionDetailById(id);
        }
    }


    @OnClick({R.id.btn_next, R.id.rel_unitName})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_next:
                if (tv_unitName.getText().toString().equals("请选择")) {
                    CustomToast.showText(context,"请先选择被检测单位！",3000,0,0).show();
                } else {
                    supervisionInspectionVo.setBusinessStatus(supervisedUnitVo.getBusinessStatus());
                    supervisionInspectionVo.setCreateUser(application.getUserName());
                    supervisionInspectionVo.setCreditCode(supervisedUnitVo.getCreditCode());
                    supervisionInspectionVo.setUnitName(supervisedUnitVo.getUnitName());
                    supervisionInspectionVo.setGender(supervisedUnitVo.getGender());
                    supervisionInspectionVo.setEconomicType(supervisedUnitVo.getEconomicType());
                    supervisionInspectionVo.setLegalRepresentative(supervisedUnitVo.getLegalRepresentative());
                    supervisionInspectionVo.setManagementAddress(supervisedUnitVo.getManagementAddress());
                    supervisionInspectionVo.setManagementCity(supervisedUnitVo.getManagementCity());
                    supervisionInspectionVo.setManagementCounty(supervisedUnitVo.getManagementCounty());
                    supervisionInspectionVo.setManagementProvince(supervisedUnitVo.getManagementProvince());
                    supervisionInspectionVo.setRegisterAddress(supervisedUnitVo.getRegisterAddress());
                    supervisionInspectionVo.setRegisterCity(supervisedUnitVo.getRegisterCity());
                    supervisionInspectionVo.setRegisterCounty(supervisedUnitVo.getRegisterCounty());
                    supervisionInspectionVo.setRegisterProvince(supervisedUnitVo.getRegisterProvince());
                    supervisionInspectionVo.setSpecialityCategory(supervisedUnitVo.getSpecialityCategory());
                    supervisionInspectionVo.setSpecialityCategoryId(supervisedUnitVo.getSpecialityCategoryId());
                    supervisionInspectionVo.setStatus(supervisedUnitVo.getStatus());
                    supervisionInspectionVo.setSuperviseDeptId(supervisedUnitVo.getSuperviseDeptId());
                    supervisionInspectionVo.setSuperviseOffice(supervisedUnitVo.getSuperviseOffice());
                    supervisionInspectionVo.setSuperviseOrgId(supervisedUnitVo.getSuperviseOrgId());
                    supervisionInspectionVo.setSuperviseSector(supervisedUnitVo.getSuperviseSector());
                    supervisionInspectionVo.setSupervisedType("0");//0为日常监督，1为双随机
                    supervisionInspectionVo.setSupervisedUnitId(supervisedUnitVo.getId());
                    supervisionInspectionVo.setNation(supervisedUnitVo.getNation());
                    supervisionInspectionVo.setSpecialityDetail(supervisedUnitVo.getSpecialityDetail());
                    supervisionInspectionVo.setSpecialityDetailId(supervisedUnitVo.getSpecialityDetailId());
                    supervisionInspectionVo.setContactNumber(supervisedUnitVo.getContactNumber());
                    supervisionInspectionVo.setContactPerson(supervisedUnitVo.getContactPerson());
                    supervisionInspectionVo.setSupervisedUnitName(supervisedUnitVo.getUnitName());
                    supervisionInspectionVo.setCertificateNo(supervisedUnitVo.getCertificateNo());
                    supervisionInspectionVo.setCertificateType(supervisedUnitVo.getCertificateType());
                    supervisionInspectionVo.setPosition(supervisedUnitVo.getPosition());
                    supervisionInspectionVo.setCreditEvaluateGrade(supervisedUnitVo.getCreditEvaluateGrade());
                    supervisionInspectionVo.setSupervisedUnitVo(supervisedUnitVo);
                    startActivity(new Intent(context, DoubleStepTwoActivity.class));
                }
                break;
            case R.id.rel_unitName:
                startActivityForResult(new Intent(context, DoubleChooseCompanyActivity.class), 1);
                break;
        }
    }

    /**
     * 为了得到传回的数据，必须在前面的Activity中（指MainActivity类）重写onActivityResult方法
     * <p>
     * requestCode 请求码，即调用startActivityForResult()传递过去的值
     * resultCode 结果码，结果码用于标识返回数据来自哪个新Activity
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (intent != null) {
            String result = intent.getExtras().getString("data");//得到新Activity 关闭后返回的数据
            if (!result.equals("")) {
                data = result;
                CleanSupervisionInspection.clean(supervisionInspectionVo);
                setData(data,null);
                Log.i("TAG", data);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CleanSupervisionInspection.clean(supervisionInspectionVo);
    }
}